package org.dromara.tearoom.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.resource.api.RemoteSmsService;
import org.dromara.resource.api.domain.RemoteSms;
import org.dromara.tearoom.config.WxHookConfig;
import org.dromara.tearoom.domain.enums.OrderStatusEnum;
import org.dromara.tearoom.domain.enums.YesOrNoEnum;
import org.dromara.tearoom.domain.vo.TerOrderVo;
import org.dromara.tearoom.domain.vo.TerRegionalInfoVo;
import org.dromara.tearoom.domain.vo.TerUserSubscriptionVo;
import org.dromara.tearoom.mapper.TerOrderMapper;
import org.dromara.tearoom.mapper.TerRegionalInfoMapper;
import org.dromara.tearoom.service.ITerUserSubscriptionService;
import org.dromara.tearoom.service.IWxMaNoticeService;
import org.dromara.common.core.utils.MoneyUtils;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 微信小程序服务通知
 * @author CKJ
 * @description: 微信小程序服务通知
 * @date 2025/4/18 15:42
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxMaNoticeServiceImpl implements IWxMaNoticeService {

    private final WxMaService wxMaService;
    private final ITerUserSubscriptionService userSubscriptionService;
    private final TerOrderMapper terOrderMapper;
    private final WxHookConfig wxHookConfig;
    private final TerRegionalInfoMapper regionalInfoMapper;
    @DubboReference
    private final RemoteSmsService remoteSmsService;


    /**
     * 需要打扫通知
     */
    @Override
    public void needClean(String orderId) {
        TerUserSubscriptionVo subscriptionVo=userSubscriptionService.queryVoByOrderId(orderId);
        if(ObjectUtil.isNotEmpty(subscriptionVo) && YesOrNoEnum.isYes(subscriptionVo.getSubscribed())){
            List<WxMaSubscribeMessage.MsgData> data = new ArrayList<>();
            data.add(new WxMaSubscribeMessage.MsgData("thing1", subscriptionVo.getRoomName()));
            data.add(new WxMaSubscribeMessage.MsgData("thing2", subscriptionVo.getRemark()));
            WxMaSubscribeMessage templateMessage = WxMaSubscribeMessage .builder()
                    .toUser(subscriptionVo.getOpenId())
                    .templateId(subscriptionVo.getTemplateId())
                    .data(data)
                    .page("/pages/mine/cleaning/cleaning")
                    .build();
            int retryCount = 1; // 重试次数
            for (int i = 0; i < retryCount; i++) {
                try {
                    wxMaService.getMsgService().sendSubscribeMsg(templateMessage);
                    break; // 发送成功，退出循环
                } catch (Exception e) {
                    e.printStackTrace();
                    if (i == retryCount - 1) {
                       log.error("消息推送失败，重试次数已达上限");
                    }
                }
            }
        }


    }

    /**
     * 太空舱下单通知
     *
     * @param orderId
     */
    @Override
    public void placeOrder(String orderId) {
        TerOrderVo terOrderVo=terOrderMapper.selectVoById(orderId);
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到订单信息");
        }
        String timeSlot=terOrderVo.getStartTime()+"至"+terOrderVo.getEndTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String contentStr = String.format(
                "尊敬的运营同事：\n【%s】新订单已生成，请及时处理！\n▸ 订单ID：%s\n▸ 用户手机：%s\n▸ 预约时段：%s\n▸ 下单时间：%s\n▸ 支付金额：￥%s元(%s)\n▸ 渠道来源：%s",
                terOrderVo.getTearoomName(),orderId,DesensitizedUtil.mobilePhone(terOrderVo.getMobile()), timeSlot, terOrderVo.getCreateTime().format(formatter), MoneyUtils.fenToYuanStr(terOrderVo.getPrepayAmount()), OrderStatusEnum.getNameByType(terOrderVo.getOrderStatus()), terOrderVo.getPaymentMethod());
        JSONObject body=new JSONObject();
        body.putOpt("msgtype","text");
        JSONObject text=new JSONObject();
        text.putOpt("content",contentStr);
        text.putOpt("mentioned_list",new String[]{"@all"});
        body.putOpt("text",text);
        HttpRequest request = HttpUtil.createPost(wxHookConfig.getPlaceOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        request.addHeaders(headers);
        String result = request.body(body.toString()).timeout(2000).execute().body();
        log.info("下单通知返回结果:{}",result);
        TerRegionalInfoVo terRegionalInfoVo=regionalInfoMapper.selectVoByTearoomId(terOrderVo.getTearoomId());
        if(ObjectUtil.isNotEmpty(terRegionalInfoVo)){
            log.info("开始发送客户短信通知");
            LinkedHashMap<String,String> smsData=new LinkedHashMap<>();
            smsData.put("1",terOrderVo.getTearoomName());
            smsData.put("2",toHourMinute(terOrderVo.getStartTime()));
            smsData.put("3",toHourMinute(terOrderVo.getEndTime()));
            smsData.put("4",terRegionalInfoVo.getAddress());
            RemoteSms remoteSms=remoteSmsService.sendMessage(terOrderVo.getMobile(),"2442846",smsData);
            log.info("客户短信通知结果:{}",remoteSms);
        }

    }

    /**
     * 清洁打扫通知
     *
     * @param orderId
     */
    @Override
    public void cleanOrder(String orderId) {
        TerOrderVo terOrderVo=terOrderMapper.selectVoById(orderId);
        if(ObjectUtil.isEmpty(terOrderVo)){
            throw new ServiceException("没有查到订单信息");
        }
        String timeSlot=terOrderVo.getStartTime()+"至"+terOrderVo.getEndTime();
        String contentStr = String.format(
                "尊敬的运营同事：\n【%s】客人订单已结束，请及时打扫！\n▸ 订单ID：%s\n▸ 用户手机：%s\n▸ 使用时段：%s\n▸ 结束时间：%s\n▸ 支付金额：￥%s元(%s)\n▸ 渠道来源：%s",
                terOrderVo.getTearoomName(),orderId,DesensitizedUtil.mobilePhone(terOrderVo.getMobile()), timeSlot, terOrderVo.getEndTime(), MoneyUtils.fenToYuanStr(terOrderVo.getPrepayAmount()), OrderStatusEnum.getNameByType(terOrderVo.getOrderStatus()), terOrderVo.getPaymentMethod());
        JSONObject body=new JSONObject();
        body.putOpt("msgtype","text");
        JSONObject text=new JSONObject();
        text.putOpt("content",contentStr);
        text.putOpt("mentioned_list",new String[]{"@all"});
        body.putOpt("text",text);
        HttpRequest request = HttpUtil.createPost(wxHookConfig.getCleanOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        request.addHeaders(headers);
        String result = request.body(body.toString()).timeout(2000).execute().body();
        log.info("清洁打扫通知返回结果:{}",result);
    }

    /**
     * 将完整日期时间转换为 HH:mm 格式
     * @param fullDateTime 格式如 2025-05-30 18:00:00
     * @return 如 18:00（无效输入返回空字符串）
     */
    private static String toHourMinute(String fullDateTime) {
        if (StrUtil.isBlank(fullDateTime)) {
            return "";
        }
        try {
            return DateUtil.format(
                    DateUtil.parse(fullDateTime),
                    "HH:mm"
            );
        } catch (Exception e) {
            // 异常处理（可记录日志）
            return ""; // 或返回原字符串 fullDateTime
        }
    }
}
